//
//  WeatherController.m
//  diaoyuren
//
//  Created by 钓鱼人 on 15/12/30.
//  Copyright © 2015年 game. All rights reserved.
//

#import "WeatherController.h"
#import "WeathNavView.h"
#import "WeathView.h"
#import "DateSelectView.h"
#import "WeathCitysCtrl.h"
#import "CGFdbmBase.h"
#import "CityModel.h"
#import "WetherModel.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import "ShareView.h"
CG_INLINE void AlertLog (NSString *titleStr,NSString *message,NSString *button1,NSString *button2)
{
    if(!titleStr)
        titleStr = @"";

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: titleStr
                                                        message: message
                                                       delegate: nil
                                              cancelButtonTitle: button1
                                              otherButtonTitles: button2,
                              nil];
    [alertView show];

}

#define footHeight (SCREEN_WIDTH-2)/3
@interface WeatherController ()<UIScrollViewDelegate,WeathCitysCtrlDeleget,ShareViewDeleget>
@property (nonatomic,strong) WeathNavView *naView;

/**
 *  承载连续七天的天气选择btn的UIScrollView
 */
@property (nonatomic,strong) UIScrollView *footScrolView;
@property (nonatomic,strong) NSString *path;

/**
 *  用于记录当前显示的 WeathView
 */
@property (nonatomic,strong) WeathView *localWeather;
@property (nonatomic,strong) UIImageView *bacGroundImg;
@property (nonatomic,assign) CGFloat contensX;
@property (nonatomic,assign) BOOL isLeft;
@property (nonatomic,assign) BOOL isRight;
@property (nonatomic,assign) NSInteger page;
@property (nonatomic,strong) WetherModel *Lastmodel;
@property (nonatomic,strong)  ShareView *shareView;
@end

@implementation WeatherController

-(NSMutableArray *)cityNameAry{

    if (!_cityNameAry) {
        _cityNameAry = [NSMutableArray array];
    }
    return _cityNameAry;
}

-(UIImageView *)bacGroundImg{
    if (!_bacGroundImg) {
        _bacGroundImg = [[UIImageView alloc]initWithFrame:self.view.frame];
        [self.view addSubview:_bacGroundImg];
        [self.view sendSubviewToBack:_bacGroundImg];
        
    }
    return _bacGroundImg;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.app.myTabBar.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
   
}
-(void)CreatNavView{
    self.naView = [[NSBundle mainBundle]loadNibNamed:@"WeathNavView" owner:nil options:nil].lastObject;
    self.naView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 64);
[self.naView.backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.naView.shareBtn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
  
    [self.view addSubview:self.naView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(navViewClick)];
    [self.naView addGestureRecognizer:tap];
}

-(UIImage*)screenView:(UIView *)view{
    
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    CGRect rect = [keyWindow bounds];
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [keyWindow.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}


-(ShareView *)shareView{

    if (!_shareView) {
        CGFloat hhh = SCREEN_HEIGHT*0.5;
        if (kDIEIsIPhone4SOrLess) {
            hhh = SCREEN_HEIGHT*0.63;
        }
        if (kDIEIsIPhone5) {
            hhh = SCREEN_HEIGHT*0.53;
        }
        if (kDIEIsIPhone6P) {
            hhh = SCREEN_HEIGHT*0.47;
        }

        _shareView = [[ShareView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - hhh, SCREEN_WIDTH, hhh)];
        
        _shareView.title = nil;
        _shareView.message =nil;
        _shareView.shareUrl = nil;
        _shareView.deleget = self;
    }
    return _shareView;
}
-(void)shareAction{
    
    self.shareView.pictureName = [self screenView:self.view];
    [self.shareView show];

}
#pragma mark---QQ空间单独事件
-(void)QzoneShare{
    NSString *utf8String = self.shareModel.share_url;
    NSString *title = self.shareModel.share_title;
    NSString *descriotion = self.shareModel.share_text;
    NSString *previewImageUrl = self.shareModel.share_img;
    
    NSArray* imageArray =@[previewImageUrl];
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKEnableUseClientShare];
        [shareParams SSDKSetupShareParamsByText:descriotion
                                         images:imageArray
                                            url:[NSURL URLWithString:utf8String]
                                          title:title
                                           type:SSDKContentTypeAudio];
        
        [ShareSDK share:SSDKPlatformSubTypeQZone
             parameters:shareParams
         onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
             
             if (state == SSDKResponseStateSuccess)
             {
                 [self.shareView fadeOut];
             }
             else if (state == SSDKResponseStateFail)
             {
                 AlertLog(@"", @"分享失败", @"确定", nil);
             }

             
         }];
        
    }
}
-(void)back{
    
    [self StopWeatherViewTime];
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark--点击添加城市
-(void)navViewClick{
    
    CATransition *transition = [CATransition animation];
    transition.duration = 0.5f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.subtype = kCATransitionFromRight;
    transition.type = @"oglFlip";
    transition.delegate = self;
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    
    WeathCitysCtrl *citys= [WeathCitysCtrl new];
    citys.modalTransitionStyle = 1;
    
    citys.cityArys=self.cityNameAry;
    citys.cityDatadic = self.cityDatadic;
    citys.deleget = self;
    [self.navigationController pushViewController:citys animated:YES];
}

-(void)RefreshCitys:(NSMutableArray *)citys{

      [self StopWeatherViewTime];
    [self setCityDatadic:self.cityDatadic];
    
}

-(UIScrollView *)scrollView{

    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64-footHeight)];
        _scrollView.showsHorizontalScrollIndicator=NO;
        _scrollView.pagingEnabled=YES;
        _scrollView.delegate = self;
        
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

-(UIScrollView *)footScrolView{

    if (!_footScrolView) {
        _footScrolView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, Height(self.scrollView)+15, SCREEN_WIDTH, footHeight-15)];
        
        [self.view addSubview:_footScrolView];
        
        _footScrolView.contentSize = CGSizeMake(footHeight*7+6, 0);
        
        _footScrolView.bounces = NO;
        _footScrolView.showsVerticalScrollIndicator = NO;
        _footScrolView.showsHorizontalScrollIndicator = NO;
    }
    return _footScrolView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     [self CreatNavView];
    
    self.shareView.alpha = 1;
}

-(void)setCityDatadic:(NSMutableDictionary *)cityDatadic{

    _cityDatadic = cityDatadic;

    self.scrollView.showsHorizontalScrollIndicator=NO;
    self.footScrolView.showsVerticalScrollIndicator = NO;
    
    self.naView.pagecont.numberOfPages = self.cityNameAry.count;
    [self.scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    for (int i=0; i<self.cityNameAry.count; i++) {
        
    
                WeathView *weathView = [[NSBundle mainBundle]loadNibNamed:@"WeathView" owner:nil options:nil].lastObject;
                weathView.frame = CGRectMake(SCREEN_WIDTH*i,0, SCREEN_WIDTH, H(self.scrollView));

                weathView.tag = 1000+i;
                
                weathView.fatherCtl = self;
                
                [self.scrollView addSubview:weathView];
        
        if (i==0) {
            
            CityModel *model = [[CityModel alloc]initWithDictionary:self.cityNameAry[i] error:nil];
            self.naView.local.text = model.name;
            WetherModel *wwModel = [_cityDatadic valueForKey:model.name];
            weathView.model = wwModel.forecast.firstObject;

            [self FootDataSetWhithData:wwModel];
            UIImage *image = [UIImage imageNamed:weathView.model.weather_bg];
            
            [UIView transitionWithView:self.bacGroundImg duration:0.7 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
                
                self.bacGroundImg.image = image;
                
            } completion:nil];
        }
        
    }
    
    self.naView.pagecont.currentPage = 0;

    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH*self.cityNameAry.count, 0);
    self.scrollView.contentOffset = CGPointMake(0, 0);
}


-(void)FootDataSetWhithData:(WetherModel *)Footmodel{

    [self.footScrolView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    for (int i = 0; i<7; i++) {
        
        DateSelectView *date  =  [[NSBundle mainBundle]loadNibNamed:@"DateSelectView" owner:nil options:nil].lastObject;
        
        date.frame = CGRectMake((footHeight+1)*i, 0, footHeight, footHeight-15);
        date.backgroundColor = RGBA(0, 0, 0, 0.5);
        date.model = Footmodel.forecast[i];
        
        if (i==0) {
            date.backgroundColor  = RGBA(149, 149, 149, 0.5);
        }
        
        [self.footScrolView addSubview:date];
        date.tag = 100000+i;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(DateClick:)];
        
        [date addGestureRecognizer:tap];
    }
}
/**
 *  日期选择 点击事件
 */
-(void)DateClick:(UITapGestureRecognizer *)tap{
    
    [self StopWeatherViewTime];
    
    for (int i=0; i<7; i++) {
        DateSelectView *data = [self.view viewWithTag:i+100000];
        
        data.backgroundColor = RGBA(0, 0, 0, 0.5);
    }
    
    DateSelectView *data = [self.view viewWithTag:tap.view.tag];

    data.backgroundColor = RGBA(149, 149, 149, 0.5);
    
    WeathView *weathView = [self.view viewWithTag:self.naView.pagecont.currentPage+1000];
    weathView.model = data.model;
    
    UIImage *image = [UIImage imageNamed:data.model.weather_bg];
    
    [UIView transitionWithView:self.bacGroundImg duration:0.7 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
        
        self.bacGroundImg.image = image;
        
    } completion:nil];
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    int indx = (int)scrollView.contentOffset.x/SCREEN_WIDTH;
    if (scrollView.contentOffset.x>self.contensX) {
        self.isLeft = NO;

        if (!self.isRight) {
        
                if (indx<self.cityNameAry.count-1) {
                    
                        [self AchiveDataWhithIndex:indx+1];
                        
                        self.isRight = YES;
            }
        }
        
    }else if (scrollView.contentOffset.x<self.contensX){

        self.isRight = NO;

        if (!self.isLeft) {
           
            if (scrollView.contentOffset.x>=0) {
                [self AchiveDataWhithIndex:indx];
                self.isLeft = YES;
               
            }
        }
    }

}

-(void)AchiveDataWhithIndex:(int)index{
    
    CityModel *model = [[CityModel alloc]initWithDictionary:self.cityNameAry[index] error:nil];
    
    WetherModel *wwModel = [_cityDatadic valueForKey:model.name];
    
    WeathView *weathView = [self.view viewWithTag:index+1000];
    weathView.model = wwModel.forecast.firstObject;
    
    UIImage *image = [UIImage imageNamed:weathView.model.weather_bg];
    
    [UIView transitionWithView:self.bacGroundImg duration:0.7 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
        
        self.bacGroundImg.image = image;
        
    } completion:nil];

}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    int index = (int)scrollView.contentOffset.x/SCREEN_WIDTH;

    self.contensX = scrollView.contentOffset.x;
    
    CityModel *model = [[CityModel alloc]initWithDictionary:self.cityNameAry[index] error:nil];
    self.naView.local.text = model.name;
    
    self.naView.pagecont.currentPage = index;
    
    WetherModel *wwModel = [_cityDatadic valueForKey:model.name];

     [self FootDataSetWhithData:wwModel];
    
    WeathForecastModel *forceModel = wwModel.forecast.firstObject;
    
    UIImage *image = [UIImage imageNamed:forceModel.weather_bg];
    
    [UIView transitionWithView:self.bacGroundImg duration:0.7 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
        
        self.bacGroundImg.image = image;
        
    } completion:nil];
    
    if (self.page==index&&self.page+self.isRight!=0) {
        WeathView *weathView = [self.view viewWithTag:index+1000];
        weathView.Datamodel = wwModel.forecast.firstObject;
        
    }
    
    WeathView *weathView = [self.view viewWithTag:index+1000];
    if (!weathView.model) {
        weathView.model = wwModel.forecast.firstObject;
    }
    
    self.page = index;
    self.isLeft = NO;
    self.isRight = NO;
}

#pragma mark---关闭显示主天气View上的 下雪 下雨 定时器
-(void)StopWeatherViewTime{
    
    for (int i=0; i<self.cityNameAry.count; i++) {
        
        WeathView *weather = [self.scrollView viewWithTag:1000+i];
        
        [weather.snowTimer invalidate];
        weather.snowTimer = nil;
        
        weather.timer = nil;
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    [self StopWeatherViewTime];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
@end
